package cn.yangliu.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 作者 杨柳
 * 创建时间 2017-08-24 18:30
 */
public class ShiroWebUtils {

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attr.getRequest();
        return request;
    }

    public static void setAttribute4Request(String name, Object value) {
        HttpServletRequest request = getRequest();
        request.setAttribute(name, value);
    }

    public static <T> T getAttributeFromRequest(String name) {
        HttpServletRequest request = getRequest();
        Object object = request.getAttribute(name);
        @SuppressWarnings("unchecked")
        T t = (T) object;
        return t;
    }

    public static Session getSession() {
        Subject subject= SecurityUtils.getSubject();
        Session session = subject.getSession();
        return session;
    }
    public static void setAttribute4Session(String name, Object value) {
        Session session = getSession();
        session.setAttribute(name, value);
    }

    public static <T> T getAttributeFromSession(String name) {
        Session session = getSession();
        Object object = session.getAttribute(name);
        @SuppressWarnings("unchecked")
        T t = (T) object;
        return t;
    }
}
